import Vue from 'vue'
import VueRouter from 'vue-router'
// import store from '@/store'
// 一级路由
import Regerster from '@/views/register/theRegister'
import Login from '@/views/login/theLogin'
import Layout from '@/views/layout/theLayout'
// 二级路由
import Home from '@/views/home/theHome'
import Article from '@/views/article/theArticle'
// Article的三级路由
import ArticleClass from '@/views/article/view/articleClass/articleClass'
import ArticleList from '@/views/article/view/articleList/articleList'
import NewArticle from '@/views/article/view/newArticle/newArticle'
import User from '@/views/user/theUser'
// User的三级路由
import UserAvatar from '@/views/user/view/userAvatar/userAvatar'
import UserInfo from '@/views/user/view/userInfo/userInfo'
import UserPassword from '@/views/user/view/userPassword/userPassword'
import { getToken } from '@/utils/storage'
Vue.use(VueRouter)

const routes = [
  { path: '/register', component: Regerster },
  { path: '/login', component: Login },
  {
    path: '/',
    component: Layout,
    redirect: '/home',

    children: [
      { path: '/home', component: Home },
      {
        path: '/article',
        component: Article,
        redirect: '/art-cate',
        children: [
          { path: '/art-cate', component: ArticleClass },
          { path: '/art-list', component: ArticleList },
          { path: '/article/newArticle', component: NewArticle }
        ]
      },
      {
        path: '/user',
        component: User,
        redirect: '/user-info',
        children: [
          { path: '/user-info', component: UserInfo },
          { path: '/user-avatar', component: UserAvatar },
          { path: '/user-pwd', component: UserPassword }
        ]
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 白名单
const whitList = ['/login', '/register']
// 设置路由前置守卫
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    // 如果不是白名单，获取用户信息
    // console.log(store.state.user.userInfo)
    // if (!(store.state.user.userInfo.username)) {
    //   store.dispatch('user/getUserInfoAction')
    // }
    // 有token，直接放行
    next()
  } else {
    // 没有token的人看看要去哪里
    if (whitList.includes(to.path)) {
      // 在白名单中直接放行
      next()
    } else {
    // 不在白名单中拦截到登录页
      next('/login')
    }
  }
})

export default router
